import os
import sys
import traceback
from datetime import datetime
import webapp2
import jinja2

jinja_env=jinja2.Environment(
    loader=jinja2.FileSystemLoader(
        os.path.join(os.path.dirname(__file__), "templates")
        ))

sys.path.insert( 0, os.path.join(os.path.dirname(__file__),
    "wtforms-1.0.2.zip") )
import wtforms
from wtforms import Form, TextField
from wtforms.ext.appengine.db import model_form
from wtforms.fields import Label

from google.appengine.api import users
from google.appengine.ext import db

from models import Board
from models import Post

BoardForm=model_form(Board, Form)

class ListBoard(webapp2.RequestHandler):
    def get(self, board_id):
        query=db.GqlQuery("SELECT * FROM Board " +
                "WHERE bid = :1 ",
                board_id )
        query.fetch(1000)
        self.response.write('Hello world! {0} count={1}'.format(board_id,
            query.count()))


class ListPost(webapp2.RequestHandler):
    def get(self, post_id):
        self.rsponse.write('Hello world!')


class AddBoard(webapp2.RequestHandler):
    def post(self):
        bid=self.request.POST.get('bid')
        board=Board.get_or_insert(bid)
        form=BoardForm(formdata=self.request.POST, obj=board)
        msg=""
        if form.validate():
            form.populate_obj(board)
            board.put()
            msg="successed!"
        else:
            msg="failure."

        self.response.write(msg)


class AddPost(webapp2.RequestHandler):
    def post(self):
        """
        Handle POST action.
        TODO: here are no input validation, better to have.
        """
        msg="failure."
        try:
            pid=self.request.POST.get('pid')
            post=Post.get_or_insert(pid)
            bid=self.request.POST.get('bid')
            board=Board.gql("WHERE bid = :1", int(bid)).get()
            post.board=board
            ishead=self.request.POST.get('ishead')
            if ishead is not None and len(ishead)>0 and ishead=='1':
                post.parent_post=None
            else:
                ppid=self.request.POST.get('parentid')
                ppost_query=Post.gql("WHERE pid = :1", int(ppid))
                if ppost_query.count()>0:
                    post.parent_post=ppost_query.get()
                else:
                    self.response.write("not found.{0}".format(
                        ppost_query.count()))
            
            title=self.request.POST.get('title')
            content=self.request.POST.get('content')
            author=self.request.POST.get('author')
            # supposed the input is '2013-01-07 16:01:59'
            posted=datetime.strptime(self.request.POST.get('posted'), "%Y-%m-%d %H:%M:%S")
            post.pid=int(pid)
            post.title=title
            post.content=content
            post.author=author
            post.posted=posted
            post.put()
            msg="successed"
        except Exception, ex:
            self.response.write(ex.args)
            self.response.write(ex.message)
            traceback.print_exc(self.response)
        self.response.write(msg)


class UpdatePost(webapp2.RequestHandler):
    def post(self, post_id):
        pass
